package com.thghh.bcode.compiler;

/**
 * @author Zhikang.Peng
 * @version 1.0
 * @email thghh@qq.com
 * @date 2020/12/10 17:11
 */
public class ByteCodeClassLoader extends ClassLoader {

    private ByteCodeJavaFileObject byteCodeJavaFileObject;

    public ByteCodeClassLoader(ClassLoader parent) {
        super(parent);
        // this is to make the stack depth consistent with 1.1
        SecurityManager security = System.getSecurityManager();
        if (security != null) {
            security.checkCreateClassLoader();
        }
    }

    public void setByteCodeJavaFileObject(ByteCodeJavaFileObject byteCodeJavaFileObject) {
        this.byteCodeJavaFileObject = byteCodeJavaFileObject;
    }

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        String className = byteCodeJavaFileObject.getClassName().replaceAll("/", ".");
        if (className.equals(name)) {
            byte[] bytecode = byteCodeJavaFileObject.getBytes();
            return defineClass(name, bytecode, 0, bytecode.length);
        }
        throw new ClassNotFoundException(name);
    }
}
